const express = require('express');
const router = express.Router();
const Message = require('../models/Message');
const { requireAuth } = require('../middleware/auth');

// 获取收件箱消息
router.get('/inbox', requireAuth, async (req, res) => {
    try {
        const messages = await Message.findAll({
            where: {
                userId: req.session.userId
            },
            order: [['createdAt', 'DESC']],
            limit: 50
        });

        res.json(messages);
    } catch (error) {
        console.error('获取收件箱消息失败:', error);
        res.status(500).json({ error: '获取消息失败' });
    }
});

// 获取未读消息数量
router.get('/unread-count', requireAuth, async (req, res) => {
    try {
        const count = await Message.count({
            where: {
                userId: req.session.userId,
                isRead: false
            }
        });

        res.json({ count });
    } catch (error) {
        console.error('获取未读消息数量失败:', error);
        res.status(500).json({ error: '获取未读消息数量失败' });
    }
});

// 标记所有消息为已读
router.post('/mark-all-read', requireAuth, async (req, res) => {
    try {
        await Message.update(
            { isRead: true },
            {
                where: {
                    userId: req.session.userId,
                    isRead: false
                }
            }
        );

        res.json({ success: true });
    } catch (error) {
        console.error('标记消息已读失败:', error);
        res.status(500).json({ error: '标记消息已读失败' });
    }
});

// 标记单条消息为已读
router.post('/mark-read/:id', requireAuth, async (req, res) => {
    try {
        const message = await Message.findOne({
            where: {
                id: req.params.id,
                userId: req.session.userId
            }
        });

        if (!message) {
            return res.status(404).json({ error: '消息不存在' });
        }

        await message.update({ isRead: true });
        res.json({ success: true });
    } catch (error) {
        console.error('标记消息已读失败:', error);
        res.status(500).json({ error: '标记消息已读失败' });
    }
});

// 删除消息
router.delete('/:id', requireAuth, async (req, res) => {
    try {
        const result = await Message.destroy({
            where: {
                id: req.params.id,
                userId: req.session.userId
            }
        });

        if (!result) {
            return res.status(404).json({ error: '消息不存在' });
        }

        res.json({ success: true });
    } catch (error) {
        console.error('删除消息失败:', error);
        res.status(500).json({ error: '删除消息失败' });
    }
});

module.exports = router; 